package api_error

import (
	"errors"
	"fmt"

	"gorm.io/gorm"
)

const (
	TokenCreateErrorCode    = 20001
	DataBaseErrorCode       = 20002
	PasswordCreateErrorCode = 20003
	NetworkErrorCode        = 20004
	IOErrorCode             = 20004
	RegexErrorCode          = 20005
	UnknownErrorCode        = 20005
)

func TokenCreateError(err error) ApiErrorType {
	return newInternalError(err, TokenCreateErrorCode, "创建Token失败")
}

func DataBaseError(err error) ApiErrorType {

	return newInternalError(err, DataBaseErrorCode, "数据库错误")
}

func DataBaseErrorOrNotFound(err error) ApiErrorType {
	if err == gorm.ErrRecordNotFound {
		return NotFound("Not Found")
	}
	return newInternalError(err, DataBaseErrorCode, "数据库错误")
}
func PasswordCreateError(err error) ApiErrorType {
	return newInternalError(err, PasswordCreateErrorCode, "构建密码出错")
}

func NetworkError(err error) ApiErrorType {
	return newInternalError(err, NetworkErrorCode, "网络请求出错")
}

func IOError(err error) ApiErrorType {
	return newInternalError(err, IOErrorCode, "IO出错")
}
func RegexErro(err error) ApiErrorType {
	return newInternalError(err, RegexErrorCode, "正则表达式错误")
}

func UnknownError(info interface{}) ApiErrorType {
	return newInternalError(errors.New(fmt.Sprintf("%s", info)), RegexErrorCode, "其他错误")
}

func newInternalError(internalErr error, errorCode int, messageFmt string, args ...interface{}) ApiErrorType {
	if apiErr, ok := internalErr.(ApiErrorType); ok {
		return apiErr
	}
	var err = new(
		code(errorCode),
		message("【内部错误】", fmt.Sprintf(messageFmt, args...), ":", internalErr.Error()),
		originError(internalErr),
		skipCallerLevel(2),
		internalError(),
	)
	return err
}
